<?php

namespace app\common\model;

use think\Model;

/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 数据层模型
 */
class Cart extends Model
{

    /**
     * 购物车商品总金额
     */
    private $cart_all_price = 0;

    /**
     * 购物车商品总数
     */
    private $cart_goods_num = 0;


    /**
     * 取属性值魔术方法
     * @access public
     * @param type $name 名称
     * @return type
     * @author csdeshang
     */
    public function __get($name)
    {
        return $this->$name;
    }

    /**
     * 检查购物车内商品是否存在
     * @access public
     * @param array $condition 检索条件
     * @return bool
     * @author csdeshang
     */
    public function checkCart($condition = array())
    {
        return db('cart')->where($condition)->find();
    }

    /**
     * 检查购物车内商品是否存在 然后返回到底存在多少件商品
     * @access public
     * @param array $condition 检索条件
     * @return bool
     * @author csdeshang
     */
    public function getgoodsCartNum($condition = array())
    {
        $cart_list = db('cart')->where($condition)->find();
        if (empty($cart_list)) {
            return array('goods_num' => 0, 'is_goods' => 0);
        } else {
            unset($condition['is_install']);
            $cart_info = db('cart')->where($condition)->select();
            return array('goods_num' => array_sum(array_column($cart_info, 'goods_num')), 'is_goods' => 1, 'cart_info' => $cart_list);
        }
    }

    /**
     * 获取购物车总数量
     * @access public
     * @param array $condition 检索条件
     * @return bool
     * @author csdeshang
     */
    public function getCartNums($user_id)
    {
        $num = db('cart')->where(['buyer_id' => $user_id])->select();
        $count = 0;
        foreach ($num as $k => $v) {
            $count += $v['goods_num'];
        }
        return $count;
    }

    /**
     * 会员购物车内商品数
     * @access public
     * @param int $memberId 会员ID
     * @return int
     * @author csdeshang
     */
    public function getCartCountByMemberId($memberId)
    {
        $memberId = intval($memberId);
        return db('cart')->where(array('buyer_id' => $memberId,))->count();
    }

    /**
     * 取得 单条购物车信息
     * @access public
     * @param array $condition 检索条件
     * @param string $field 字段
     * @return array
     * @author csdeshang
     */
    public function getCartInfo($condition = array(), $field = '*')
    {
        return db('cart')->field($field)->where($condition)->find();
    }

    /**
     * 将商品添加到购物车中
     * @access public
     * @param array $data 商品数据信息
     * @param string $save_type 保存类型，可选值 db,cookie
     * @param int $quantity 购物数量
     * @return type
     * @author csdeshang
     */
    public function addCart($data = array(), $save_type = '', $quantity = null, $address_id = '1')
    {
        $method = '_addCart' . ucfirst($save_type);
        $result = $this->$method($data, $quantity, $address_id);
        if (!$result) {
            return false;
        }
        //更改购物车总商品数和总金额，传递数组参数只是给DB使用
        $this->getCartNum($save_type, array('buyer_id' => isset($data['buyer_id']) ? $data['buyer_id'] : 0));
        return $result;
    }

    /**
     * 添加数据库购物车
     * @access public
     * @param array $goods_info 商品信息
     * @param int $quantity 购物数量
     * @return type
     * @author csdeshang
     */
    private function _addCartDb($goods_info = array(), $quantity, $address_id)
    {
        //验证购物车商品是否已经存在
        $condition = array();
        $condition['goods_id'] = $goods_info['goods_id'];
        $condition['is_install'] = $goods_info['is_install'];
        $condition['buyer_id'] = $goods_info['buyer_id'];
        if (isset($goods_info['bl_id'])) {
            $condition['bl_id'] = $goods_info['bl_id'];
        } else {
            $condition['bl_id'] = 0;
        }
        //如果购物车存在
        $check_cart = $this->getgoodsCartNum($condition);
        //如果购物车内存在商品 并且商品状态为失效的话 更新购物车商品状态
        if ($check_cart['is_goods'] == 1 && $check_cart['cart_info']['status'] == 1) {
            db('cart')->where(['cart_id' => $check_cart['cart_info']['cart_id']])->data(['status' => 0])->update();
        }
        #更新商品价格
        $store_id = get_parent_store_id();
        $supplier_type = get_supplier_type();

        #计算安装费
        $address_info = db('address')->where(['address_id' => $address_id])->find();
        if (!$address_info) {
            return json_fail_return('地址不存在');
        }
        if ($goods_info['is_install'] == 1) {
            if ($goods_info['install_money']) {
                $sum_install_money = get_install_money($address_info['area_id'], (float)$goods_info['install_money']);
            } else {
                $sum_install_money = 0;
            }
        }

        if ($check_cart['is_goods']) {
            /* if ($quantity != $check_cart['cart_info']['goods_num']) {*/
            if ($quantity > $goods_info['goods_storage']) {
                $this->error_code = 10001;
                $this->error_message = '库存不足';
                return false;
            }
            //通过折扣id 获取折扣信息
            $discount_id = input('param.discount_id', '');
            // $array['discount_id'] = input('param.discount_id', '');
            $discount_info = db('pxianshi')->where(['xianshi_id' => $discount_id])->find();

            //判断折扣
            if (!empty($discount_id)) {
                //折扣信息入库
                $array['discount_id'] = $discount_id;
                $array['is_discount'] = empty($discount_id) ? 0 : 1;
                $array['discount_rate'] = $discount_info['discount_rate'];
                $array['discount_starttime'] = $discount_info['xianshi_starttime'];
                $array['discount_endtime'] = $discount_info['xianshi_end_time'];
                //折扣率
                $rate = $array['discount_rate'] / 100;
            }

            #shen 判断价格是否相同
            if ($supplier_type == 1) {
                #加价
                $y_goods_info = db('y_goods')->where('store_id', $store_id)->where('goods_id', $goods_info['goods_id'])->find();
                // p($goods_info);die;
                if ($goods_info['is_install'] == 1) {
                    #含有安装
                    $new_goods_price = $sum_install_money + (float)$goods_info['gu_final_price'] + (float)$y_goods_info['price'];
                } else {
                    $new_goods_price = (float)$goods_info['gu_final_price'] + (float)$y_goods_info['price'];
                }
            } else {
                #按照提成走
                if ($goods_info['is_install'] == 1) {
                    #含有安装
                    $new_goods_price = $sum_install_money + (float)$goods_info['ti_final_price'];
                } else {
                    $new_goods_price = (float)$goods_info['ti_final_price'];
                }

            }
            // if ($quantity == $check_cart['cart_info']['goods_num']) {
            //     $array['goods_num'] = $quantity + 1;
            // } else {
            //     $array['goods_num'] = $quantity;
            // } 
            if ($quantity == $check_cart['cart_info']['goods_num']) {
                $array['goods_num'] = $quantity + $check_cart['cart_info']['goods_num'];
            } else {
                $array['goods_num'] = $quantity + $check_cart['cart_info']['goods_num'];
            }
            //判断是否有折扣
            if ($discount_id) {
                //原价
                $array['original_price'] = (float)$new_goods_price;
                //折扣后的价格
                $array['goods_price'] = (float)$new_goods_price * (1 - $rate);
            } else {
                $array['original_price'] = (float)$new_goods_price;
                $array['goods_price'] = (float)$new_goods_price;
            }

            $array['address_id'] = $address_id; #当前加入购物车的地址
            $array['install_hour'] = $goods_info['install_money']; #安装工时
            /*p($check_cart['cart_info']['goods_price']);
            echo '----';
            p($new_goods_price);die;*/
            if ($check_cart['cart_info']['goods_price'] != $new_goods_price) {
                //如果商品存在则更新数量 及价格
                if ($goods_info['is_install'] == 1) {
                    $array['install_money'] = $sum_install_money;
                }
                return db('cart')->where($condition)->data($array)->update();

            } else {
                //如果商品存在则更新数量
                return db('cart')->where($condition)->data($array)->update();
            }

            /* } else {
                 return 1;
             }*/

        } else {
            // p($goods_info);die;

            // 1、计算出商品的真实价格（供应商，平台，运营商的价格） 2、计算活动后的价格 3、最终的价格加上安装费 才是订单的价格

            //如果商品不存在则插入
            $array = array();
            $array['buyer_id'] = $goods_info['buyer_id'];
            $array['store_id'] = $goods_info['store_id']; #供应商id
            $array['goods_id'] = $goods_info['goods_id'];
            $array['spec_values'] = $goods_info['spec_values'];
            $array['status'] = 0;
            $array['goods_commonid'] = $goods_info['goods_commonid']; #供应商id
            $array['yun_store_id'] = $store_id;
            $array['goods_name'] = $goods_info['goods_name'];
            $array['address_id'] = $address_id;
            $array['install_hour'] = $goods_info['install_money']; #安装工时

            //通过折扣id 获取折扣信息
            $discount_id = input('param.discount_id', '');
            $discount_info = db('pxianshi')->where(['xianshi_id' => $discount_id])->find();

            //判断折扣
            if (!empty($discount_id)) {
                //折扣信息入库
                $array['discount_id'] = $discount_id;
                $array['is_discount'] = empty($discount_id) ? 0 : 1;
                $array['discount_rate'] = $discount_info['discount_rate'];
                $array['discount_starttime'] = $discount_info['xianshi_starttime'];
                $array['discount_endtime'] = $discount_info['xianshi_end_time'];
                //折扣率
                $rate = $array['discount_rate'] / 100;
            }

            #1、计算商品的真实价格
            if ($supplier_type == 1) {
                #加价
                $y_goods_info = db('y_goods')->where('store_id', $store_id)->where('goods_id', $goods_info['goods_id'])->find();
                // p($goods_info);die;
                if ($goods_info['is_install'] == 1) {
                    #含有安装
                    $array['spec_values'] = '含有安装费,' . $goods_info['spec_values'];
                    $array['goods_price'] =  (float)$goods_info['gu_final_price'] + (float)$y_goods_info['price'];
                    $array['is_install'] = 1;
                    $array['install_money'] = $sum_install_money;
                } else {
                    $array['goods_price'] = (float)$goods_info['gu_final_price'] + (float)$y_goods_info['price'];
                    $array['is_install'] = 0;
                    $array['install_money'] = 0;
                }
            } else {
                #按照提成走
                if ($goods_info['is_install'] == 1) {
                    #含有安装
                    $array['spec_values'] = '含有安装费,' . $goods_info['spec_values'];
                    $array['goods_price'] = (float)$goods_info['ti_final_price'];
                    $array['is_install'] = 1;
                    $array['install_money'] = $sum_install_money;
                } else {
                    $array['goods_price'] = (float)$goods_info['ti_final_price'];
                    $array['is_install'] = 0;
                    $array['install_money'] = 0;
                }
            }

            #2、判断活动
            //判断是否有折扣
            if ($discount_id) {
                //原价
                $array['original_price'] = (float)$array['goods_price'];
                //折扣后的价格
                $array['goods_price'] = (float)$array['goods_price'] * (1 - $rate);
            } else {
                $array['original_price'] = (float)$array['goods_price'];
            }

            #3、判断是否有安装费
            if($goods_info['is_install'] == 1){
                $array['goods_price'] += $array['install_money']; 
            }

            $array['goods_num'] = $quantity;
            $array['goods_image'] = $goods_info['goods_image'];
            $array['store_name'] = $goods_info['store_name'];
            $array['bl_id'] = isset($goods_info['bl_id']) ? $goods_info['bl_id'] : 0;

            return db('cart')->insertGetId($array);
        }


    }

    /**
     * 添加到cookie购物车,最多保存5个商品
     * @access public
     * @param array $goods_info 商品信息
     * @param int $quantity 购物数量
     * @return bool
     * @author csdeshang
     */
    private function _addCartCookie($goods_info = array(), $quantity = null)
    {
        //去除斜杠
        $cart_str = get_magic_quotes_gpc() ? stripslashes(cookie('cart')) : cookie('cart');
        $cart_str = base64_decode(ds_decrypt($cart_str));
        $cart_array = @unserialize($cart_str);
        $cart_array = !is_array($cart_array) ? array() : $cart_array;
        if (count($cart_array) >= 5) {
            $this->error_code = 10001;
            $this->error_message = '未登录状态最多保存5个商品';
            return false;
        }

        if (in_array($goods_info['goods_id'], array_keys($cart_array))) {
            //如果购物车存在则更新数量
            $cart_array[$goods_info['goods_id']] = array(
                'store_id' => $goods_info['store_id'],
                'goods_id' => $goods_info['goods_id'],
                'goods_name' => $goods_info['goods_name'],
                'goods_price' => $goods_info['goods_price'],
                'goods_image' => $goods_info['goods_image'],
                'goods_num' => $cart_array[$goods_info['goods_id']]['goods_num'] + $quantity
            );
            cookie('cart', ds_encrypt(base64_encode(serialize($cart_array))), 24 * 3600);
            return true;
        } else {
            $cart_array[$goods_info['goods_id']] = array(
                'store_id' => $goods_info['store_id'],
                'goods_id' => $goods_info['goods_id'],
                'goods_name' => $goods_info['goods_name'],
                'goods_price' => $goods_info['goods_price'],
                'goods_image' => $goods_info['goods_image'],
                'goods_num' => $quantity
            );
            cookie('cart', ds_encrypt(base64_encode(serialize($cart_array))), 24 * 3600);
            return true;
        }


    }

    /**
     * 更新购物车
     * @access public
     * @param array $data 商品信息
     * @param array $condition 检索条件
     * @return bool
     * @author csdeshang
     */
    public function editCart($data, $condition)
    {
        $result = db('cart')->where($condition)->update($data);
        if ($result) {
            $this->getCartNum('db', array('buyer_id' => $condition['buyer_id']));
        }
        return $result;
    }

    /**
     * 购物车列表
     * @access public
     * @param string $type 存储类型 db,cookie
     * @param array $condition 检索条件
     * @param int $limit 限制
     * @return array
     * @author csdeshang
     */
    public function getCartList($type, $condition = array(), $limit = '')
    {
        if ($type == 'db') {
            $cart_list = db('cart')->where($condition)->field('*,goods_price as cart_price')->limit($limit)->select();
        } elseif ($type == 'cookie') {
            //去除斜杠
            $cart_str = get_magic_quotes_gpc() ? stripslashes(cookie('cart')) : cookie('cart');
            $cart_str = base64_decode(ds_decrypt($cart_str));
            $cart_list = @unserialize($cart_str);
        }
        $cart_list = is_array($cart_list) ? $cart_list : array();
        //顺便设置购物车商品数和总金额
        $this->cart_goods_num = count($cart_list);
        $cart_all_price = 0;
        if (is_array($cart_list)) {
            foreach ($cart_list as $val) {
                $cart_all_price += $val['goods_price'] * $val['goods_num'];
            }
        }
        $this->cart_all_price = ds_price_format($cart_all_price);
        return !is_array($cart_list) ? array() : $cart_list;
    }

    /**
     * 删除购物车商品
     * @access public
     * @param string $type 存储类型 db,cookie
     * @param array $condition 检索条件
     * @return bool
     * @author csdeshang
     */
    public function delCart($type, $condition = array())
    {

        if ($type == 'db') {
            //  p($condition);die;
            if ($condition['cart_id']['0'] == 'in') {
                if (!strpos($condition['cart_id']['1'], ',')) {
                    $result = db('cart')->where($condition)->delete();
                } else {
                    $ids = explode(',', $condition['cart_id']['1']);

                    foreach ($ids as $k => $v) {
                        $result = db('cart')->where(['cart_id' => $v, 'buyer_id' => $condition['buyer_id']])->delete();
                    }

                }
            } else {
                if (strpos($condition['cart_id'], ',')) {
                    $result = db('cart')->where($condition)->delete();
                } else {
                    $ids = explode(',', $condition['cart_id']);

                    foreach ($ids as $k => $v) {
                        $result = db('cart')->where(['cart_id' => $v, 'buyer_id' => $condition['buyer_id']])->delete();
                    }

                }

            }

        } elseif ($type == 'cookie') {
            $cart_str = get_magic_quotes_gpc() ? stripslashes(cookie('cart')) : cookie('cart');
            $cart_str = base64_decode(ds_decrypt($cart_str));
            $cart_array = @unserialize($cart_str);
            if (key_exists($condition['goods_id'], (array)$cart_array)) {
                unset($cart_array[$condition['goods_id']]);
            }
            cookie('cart', ds_encrypt(base64_encode(serialize($cart_array))), 24 * 3600);
            $result = true;
        }
        //重新计算购物车商品数和总金额
        if ($result) {
            $this->getCartNum($type, array('buyer_id' => isset($condition['buyer_id']) ? $condition['buyer_id'] : 0));
        }
        return $result;
    }

    /**
     * 清空购物车
     * @access public
     * @param string $type 存储类型 db,cookie
     * @param array $condition 检索条件
     * @return bool
     * @author csdeshang
     */
    public function clearCart($type, $condition = array())
    {
        if ($type == 'cookie') {
            //登录后清空cookie中保存的商品信息
            cookie('goods_cart', NULL);
            cookie('cart_count', NULL);
            cookie('cart', NULL);
        } else if ($type == 'db') {
            //数据库暂无浅清空操作
        }
    }

    /**
     * 计算购物车总商品数和总金额
     * @access public
     * @param string $type 购物车信息保存类型 db,cookie
     * @param array $condition 只有登录后操作购物车表时才会用到该参数
     * @return type
     * @author csdeshang
     */
    public function getCartNum($type, $condition = array())
    {

        if ($type == 'db') {
            $cart_all_price = 0;
            $condition['status'] = 0;
            $cart_goods = $this->getCartList('db', $condition);
            $this->cart_goods_num = count($cart_goods);
            if (!empty($cart_goods) && is_array($cart_goods)) {
                foreach ($cart_goods as $val) {
                    $cart_all_price += $val['goods_price'] * $val['goods_num'];
                }
            }
            $this->cart_all_price = ds_price_format($cart_all_price);
        } elseif ($type == 'cookie') {
            $cart_str = get_magic_quotes_gpc() ? stripslashes(cookie('cart')) : cookie('cart');
            $cart_str = base64_decode(ds_decrypt($cart_str));
            $cart_array = @unserialize($cart_str);
            $cart_array = !is_array($cart_array) ? array() : $cart_array;
            $this->cart_goods_num = count($cart_array);
            $cart_all_price = 0;
            foreach ($cart_array as $v) {
                $cart_all_price += floatval($v['goods_price']) * intval($v['goods_num']);
            }
            $this->cart_all_price = $cart_all_price;
        }
        @cookie('cart_goods_num', $this->cart_goods_num, 2 * 3600);
        return $this->cart_goods_num;
    }

    /**
     * 登录之后,把登录前购物车内的商品加到购物车表
     * @access public
     * @param array $member_info 会员信息
     * @param int $store_id 店铺ID
     * @return type
     * @author csdeshang
     */
    public function mergeCart($member_info = array(), $store_id = null)
    {
        if (!$member_info['member_id'])
            return;
        // $save_type = config('cache.type') != 'file' ? 'cache' : 'cookie';
        $save_type = 'cookie';
        $cart_new_list = $this->getCartList($save_type);
        if (empty($cart_new_list))
            return;

        //取出当前DB购物车已有信息
        $cart_cur_list = $this->getCartList('db', array('buyer_id' => $member_info['member_id']));

        //数据库购物车已经有的商品，不再添加
        if (!empty($cart_cur_list) && is_array($cart_cur_list) && is_array($cart_new_list)) {
            foreach ($cart_new_list as $k => $v) {
                if (!is_numeric($k) || in_array($k, array_keys($cart_cur_list))) {
                    unset($cart_new_list[$k]);
                }
            }
        }

        //查询在购物车中,不是店铺自己的商品，未禁售，上架，有库存的商品,并加入DB购物车
        $goods_model = model('goods');
        $condition = array();
        if (!empty($store_id)) {
            $condition['store_id'] = array('neq', $store_id);
        }
        $condition['goods_id'] = array('in', array_keys($cart_new_list));
        $goods_list = $goods_model->getGoodsOnlineList($condition);
        if (!empty($goods_list)) {
            foreach ($goods_list as $goods_info) {
                $goods_info['buyer_id'] = $member_info['member_id'];
                $this->addCart($goods_info, 'db', $cart_new_list[$goods_info['goods_id']]['goods_num']);
            }
        }
        //最后清空登录前购物车内容
        $this->clearCart($save_type);
    }


}

?>
